package io.persimmon.springboot.strategy;

import io.persimmon.core.module.strategy.Strategy;
import lombok.Data;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Data
public class StrategyManager {
    @Autowired
    private List<Strategy<?, ?>> strategyList;

    private Map<Class<?>, Map<?, Strategy>> strategyMap = new HashMap<>();

    @PostConstruct
    public void init() {
        Map<? extends Class<?>, List<Strategy<?, ?>>> map = strategyList.stream()
                .collect(Collectors.groupingBy(Strategy::strategyParent));

        strategyMap = new HashMap<>();
        map.forEach((k, v) -> {
            strategyMap.put(k, v.stream()
                    .collect(Collectors.toMap(Strategy::strategyLabel, e -> e, (v1, v2) -> v1)));
        });
    }

    public <Code, Parent> Parent getStrategy(Code code, Class<Parent> parent) {
        Map<?, Strategy> map = this.strategyMap.get(parent);
        if (MapUtils.isEmpty(map)) {
            return null;
        }
        return (Parent) map.get(code);
    }
}
